package com.ws.common.util;

import com.ws.common.vo.SocketMsgDataVo;

import java.io.*;
import java.net.Socket;

public class SocketUtil {

    public static Socket createClientSocket(String host, int port) throws IOException {
        Socket socket = new Socket(host, port);
        return socket;
    }

    public static void closeSocket(Socket socket) {
        if (socket != null && !socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeMsgData(DataOutputStream dataOutputStream, SocketMsgDataVo msgDataVo) throws IOException {
        byte[] data = msgDataVo.getBody().getBytes();
        int len = data.length;
        dataOutputStream.writeByte(msgDataVo.getType());
        dataOutputStream.writeInt(len);
        dataOutputStream.write(data);
        dataOutputStream.flush();
    }

    public static String readMsgData(InputStream inputStream) throws IOException {
       /* byte[] tt = new byte[1024*10];
        while ((inputStream.read(tt)) != -1) {
           String tzt=new String(tt,"utf-8");
            if (!StringUtils.isEmpty(tzt)) {
                return tzt;
            }
        }*/

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedInputStream bufferIn = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1];
        int len;
        byte[] lenBytes = new byte[6];
        bufferIn.read(lenBytes);
        String str=new String(lenBytes).replaceAll("\\^", "").replaceAll("\\$","");
       /* String str=new String(lenBytes).split("\\$")[0].replaceAll("\\^", "");*/
        if(!isNumber(str)){
           return null;
        }
        Integer dataLen = Integer.valueOf(str)-1;
        while ((len = bufferIn.read(buf)) != -1) {
            byteArrayOutputStream.write(buf, 0, len);
            dataLen = dataLen - len;
            if (dataLen <= 0)
                break;
        }
        return new String(byteArrayOutputStream.toByteArray(), "GBK");
    }

    private static boolean isNumber(String str){
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    public static void main(String[] args) {
        String str="{\"key\":\"taxi5B4ABE3AA4E712-\"}";
        System.out.println(str.length());
    }
}
